package com.engineering.elink.util.verify;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;

public final class CodeImageGenerator {
	 private final static int DEF_WIDTH = 90;
	 private final static int DEF_HEIGHT = 30;
	
	 private String code;
	 private int width;
	 private int height; 
	 private BufferedImage image;
	
	 public CodeImageGenerator(String verifyCode) {
		 this.width = DEF_WIDTH;
		 this.height = DEF_HEIGHT;
		generateCodeImage(verifyCode);
	}
	
	 private void generateCodeImage(String verifyCode) { 
		 // create the image
		 image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
		 Graphics g = image.getGraphics();
		
		 // set the background color 
		 g.setColor(new Color(0xDCDCDC)); 
		 g.fillRect(0, 0, width, height);
		
		 // draw the border
		g.setColor(Color.black);
		 g.drawRect(0, 0, width - 1, height - 1);
		
		 // set the font
		 g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
		
		 // create a random instance to generate the codes
		 Random random = new Random();
		
		 // make some confusion
		 for (int i = 0; i < 50; i++) { 
			 int x = random.nextInt(width); 
			 int y = random.nextInt(height);
			 g.drawOval(x, y, 0, 0);
		 }
	
		 // generate a random code
		 for (int i = 0; i < verifyCode.length(); i++) {
			 g.drawString(verifyCode.charAt(i)+"", 23*i+6, 23);
		}
		
		g.dispose();
	}
	
	 public BufferedImage getImage() {
		 return image;
	}
	
	 public String getCode() {
		 return code;
	}
	
	 public static String generateBase64Image (String verifyCode) throws IOException {
		 String imgPath = "D:\\bt1update\\codeImage1.jpeg";
		 File imgFile = new File(imgPath);
		 CodeImageGenerator cig = new CodeImageGenerator(verifyCode);
		 ImageIO.write(cig.getImage(),"JPEG", imgFile);
		 String base64Img = ImageGenerate.GetImageStr(imgPath);
		 return "data:image/jpg;base64," + base64Img;
	 }
	 
	 public static void main(String[] args) throws Exception {
		 
			CodeImageGenerator.generateBase64Image("GASD");
	}
	
}